package com.musiklegal;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class PlaylistSender implements Serializable 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final boolean URLContainer = false;
	List<URLContainer> listSong;
	
	private PlaylistSender()
	{
		listSong = new ArrayList<URLContainer>();
	}
	
	 void addSong(File g3n,Context c)
	{
		
		 
		byte data []  = new byte[256];
		try {
			FileInputStream fis = new FileInputStream(g3n);
			fis.read(data);
			String s = new String(data,"ISO-8859-1");
			String idring = s.substring(147, 177).trim();
			String api =  s.substring(177, 181).trim();
			String startdate = MusikLegal.mPreferences.getString("START", "");
//			String enddate = MusikLegal.mPreferences.getString("SubDate", "");
			
				
			int sel ;
			if(MusikLegal.current_date!=null)
			sel = (int) PlaylistSender.durationDay(parseToUTC(startdate), parseToUTC(MusikLegal.current_date));
			else
				sel = (int) PlaylistSender.durationDay(parseToUTC(startdate), Calendar.getInstance().getTime());
			//Log.d("add to queue",sel+" "+idring+" "+api);
			String send = sel + "|" + idring + "|" + api;
			String username =MusikLegal.mPreferences.getString("UserName", "");
			String password = MusikLegal.mPreferences.getString("PassWord", "") ;
			
			String subsid =MusikLegal.mPreferences.getString("SubId", "");
			URLContainer uc = new URLContainer(username,password,MusikLegal.getUID(c),subsid,send);
			listSong.add(uc);
			Log.d("add song",uc.toString() );
			fis.close();
			save();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void save() throws IOException
	{
		File f = new File(MusikLegal.mainFolder+"logplay");
		if(!f.exists())
			f.createNewFile();
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
		oos.writeObject(this);
		oos.close();
		
	}
	
	public static Date parseToUTC(String date) 
	{
		String [] tgl = date.split("-");
		
		Calendar c =Calendar.getInstance();
		int year,month,datE;
		try
		{
			year = Integer.parseInt(tgl[0]);
			month = Integer.parseInt(tgl[1])-1;
			datE = Integer.parseInt(tgl[2]);
			c.set(year, month, datE);
		}
		catch(NumberFormatException e)
		{
			return null;
		}

		return c.getTime();
	}
	
	
	public static void sendSong(File g3n,Context c) throws ParserConfigurationException, SAXException, IllegalStateException, IOException
	{
		
		byte data []  = new byte[256];
		
			FileInputStream fis = new FileInputStream(g3n);
			fis.read(data);
			String s = new String(data,"ISO-8859-1");
			String idring = s.substring(147, 177).trim();
			String api =  s.substring(177, 181).trim();
			String startdate = MusikLegal.mPreferences.getString("START", "");
			String enddate = MusikLegal.mPreferences.getString("SubDate", "");
			int sel = (int) durationDay(parseToUTC(startdate),parseToUTC(MusikLegal.current_date));
			//Log.d("add to queue",sel+" "+idring+" "+api);
			String send = sel + "|" + idring + "|" + api;
			String username =MusikLegal.mPreferences.getString("UserName", "");
			String password = MusikLegal.mPreferences.getString("PassWord", "") ;
			String subsid =MusikLegal.mPreferences.getString("SubId", "");
			String uid = MusikLegal.getUID(c);
			
			  HttpClient client = new DefaultHttpClient();
			  HttpPost subs = new HttpPost("http://secure.musiklegal.com/subscription/play");
			  List<BasicNameValuePair> postData= new ArrayList<BasicNameValuePair>(4);
			  postData.add(new BasicNameValuePair("USERNAME",username));
		      postData.add(new BasicNameValuePair("UID", uid));
		      postData.add(new BasicNameValuePair("PASSWORD", password ));
		      postData.add(new BasicNameValuePair("SUBSCRIPTION_ID",subsid ));
		      postData.add(new BasicNameValuePair("IDRINGS", send));
		      
		      UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(postData,HTTP.UTF_8);
		      subs.setEntity(s_entity);
		      HttpResponse response3 = client.execute(subs);
		      HttpEntity responseEntity3 = response3.getEntity();
		      SAXParserFactory bpf = SAXParserFactory.newInstance();
		      SAXParser bp = bpf.newSAXParser();
		      XMLReader br = bp.getXMLReader();
		      LoginHandler subsHand = new LoginHandler();
		      br.setContentHandler(subsHand);
		      br.parse(new InputSource(responseEntity3.getContent()));
		      ParsedLoginDataSet subset = subsHand.getParsedLoginData();
			
		      Log.d("send playlist",subset.getExtractedString());
		      if (subset.getExtractedString().compareTo("SUCCESS")==0) {
		    	  
		    	Log.d("send", username+" "+password+" "+uid+" "+subsid+" "+send);
		      }
		    	fis.close();
		
		
	}
	
	
	
	public synchronized void  send() throws IllegalStateException, IOException, SAXException, ParserConfigurationException
	{
		
		List<URLContainer> tes = new CopyOnWriteArrayList<URLContainer>(listSong);
		
		 for(URLContainer valData : tes)
		 {
			  
		      HttpClient client = new DefaultHttpClient();
			  HttpPost subs = new HttpPost("http://secure.musiklegal.com/subscription/play");
			  List<BasicNameValuePair> postData= new ArrayList<BasicNameValuePair>();
			  postData.add(new BasicNameValuePair("USERNAME",valData.username ));
		      postData.add(new BasicNameValuePair("UID", valData.uid));
		      postData.add(new BasicNameValuePair("PASSWORD", valData.password ));
		      postData.add(new BasicNameValuePair("SUBSCRIPTION_ID",valData.sub_id ));
		      postData.add(new BasicNameValuePair("IDRINGS", valData.idrings));
		      Log.e("send", valData.toString());
		      UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(postData,HTTP.UTF_8);
		      subs.setEntity(s_entity);
		      HttpResponse response3 = client.execute(subs);
		      HttpEntity responseEntity3 = response3.getEntity();
		      SAXParserFactory bpf = SAXParserFactory.newInstance();
		      SAXParser bp = bpf.newSAXParser();
		      XMLReader br = bp.getXMLReader();
		      LoginHandler subsHand = new LoginHandler();
		      br.setContentHandler(subsHand);
		      br.parse(new InputSource(responseEntity3.getContent()));
		      ParsedLoginDataSet subset = subsHand.getParsedLoginData();
		      
		      //Log.d("send playlist",subset.getExtractedString());
		      if (subset.getExtractedString().compareTo("SUCCESS")==0) 
		      {
		    	  
		    	//Log.d("send "+listSong.size(), valData.toString());
		    	listSong.remove(valData);
		      }
		     
		      
		    }
		 save();
		
	}
	
	public static PlaylistSender loadLog()
	{ 
		File f = new File(MusikLegal.mainFolder+"logplay");
		if(!f.exists())
			return new PlaylistSender();
		else
		{
			try {
				ObjectInputStream or  = new ObjectInputStream(new FileInputStream(f));
				PlaylistSender ps = (PlaylistSender) or.readObject();
				or.close();
				
				return ps;
			} catch (StreamCorruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return new PlaylistSender();
	}
	
	static long durationDay(Date start, Date end)
	{
		long d = (end.getTime()- start.getTime())/(1000*60*60*24)+1;
//		Log.i("start", start.toString());
//		Log.i("end",end.toString());
		return  d;
	}
	
	static class URLContainer implements Serializable
	{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1850671328974056231L;
		String username,uid,idrings,sub_id,password;
		public URLContainer(String usrnm, String pass,String uid,String subsid,String idringS)
		{
			username = usrnm;
			password = pass;
			sub_id = subsid;
			idrings = idringS;
			this.uid = uid;
			
		}
		
		public String toString()
		{
			return username+" "+password+" "+uid+" "+sub_id+" "+idrings;
		}
		
	}
	
	
}
